// Runner.cpp
//
// Copyright (c) 2008 Bojan Rajkovic
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//

#include "../include/Runner.h"

void Runner::Terminate() {
		// log that we're dying--no need to clean up Keycounter anyway, the destructor will take care of it.
		Utility::LogMessage(_("Caught a sigterm or int, will shut down now."), M_INFO);
		Pulse::SavePulseFile(this->keycounter->Keys());
		delete this->keycounter;
		delete this->commandInterface;
}

void Runner::SendPulse() {
		this->keycounter->Pulse();
}

Runner::Runner(std::string EventDevice, std::string OutputFile) {
		this->keycounter = new Keycounter(EventDevice, OutputFile);
		this->commandInterface = new CommandInterface(this->keycounter);
}

Runner::~Runner() {
}

void Runner::Run() {
	
		Utility::LogMessage("Running runner.", M_INFO);
	
		// Start threads for the keycounter and command interface.
		// I really dislike this ugly boost::bind hack, but it's the best way to use boost::thread in an OOP manner 
		boost::thread keycounterThread(boost::bind(&LinPulse::Keycounter::Run, this->keycounter));
		boost::thread commandInterfaceThread(boost::bind(&LinPulse::CommandInterface::Run, this->commandInterface));
	
		// Let's drop our root privileges. We're gonna use the nobody user.
		struct passwd* pw = getpwnam("nobody");
		setuid(pw->pw_uid);
		setgid(pw->pw_gid);
		Utility::LogMessage(_("Dropped our root privileges, proceeding as 'nobody' user."), M_INFO);
	
		// wait for the thread to finish--this'll never happen, but that's okay.
		keycounterThread.join();
		commandInterfaceThread.join();
}
